import { useMemo, useEffect, useState, useRef } from "react";
import { useFrame } from "@react-three/fiber";
import { PositionalAudio, useAnimations, useGLTF } from "@react-three/drei";
import { CapsuleCollider, RigidBody, euler, quat } from "@react-three/rapier";
import { SkeletonUtils } from "three-stdlib";
import { PLAYER_STATUS } from "../../config/enum";
import audios from "../../assets/audios";
import { players } from "../../utils";

useGLTF.preload("./player/actor.gltf");

const JUMP = 7; // 跳跃速度
export default ({ id }) => {
  /*----------------------------变量命名------------------------------*/
  // 加载模型
  const { scene, animations }: any = useGLTF("./player/actor.gltf");

  // 克隆网格
  const clone = useMemo(() => SkeletonUtils.clone(scene), [scene]);
  // 获取动画
  const { ref, actions, names }: any = useAnimations(animations, clone);
  const [status, setStatus] = useState(PLAYER_STATUS.idle); // 玩家状态
  const playerRef: any = useRef(); // 玩家的引用
  const footsteps: any = useRef(); // 脚步音频

  /*----------------------------生命周期-------------------------------*/
  // 运动状态
  useEffect(() => {
    switch (status) {
      case PLAYER_STATUS.run:
        actions[names[1]]?.fadeOut(0.2);
        actions[names[2]]?.reset().fadeIn(0.2).play();
        footsteps.current?.play();
        break;
      case PLAYER_STATUS.walk:
        actions[names[1]]?.fadeOut(0.2);
        actions[names[0]]?.reset().fadeIn(0.2).play();
        footsteps.current?.play();
        break;
      default:
        actions[names[2]]?.fadeOut(0.2);
        actions[names[1]]?.reset().fadeIn(0.2).play();
        footsteps.current?.stop();
        break;
    }
  }, [status]);

  useFrame(() => {
    if (!playerRef?.current) return;
    const player = players.get(id);
    if (player) {
      const { velocity, position, jump } = player;
      if (position) {
        playerRef.current.setTranslation(position, true);
        // start.copy(position);
        console.log("新成员", player.id, position);
        delete player.position;
      } else {
        jump && playerRef.current.setLinvel({ x: 0, y: JUMP, z: 0 });
        playerRef.current.setLinvel({
          x: velocity.x,
          y: playerRef.current.linvel().y,
          z: velocity.z,
        });
      }
      if (velocity.x !== 0 || velocity.z !== 0) {
        setStatus(PLAYER_STATUS.run);
        rotation(velocity);
      } else {
        setStatus(PLAYER_STATUS.idle);
      }
      // reset();
    }
  });
  /*----------------------------辅助函数-------------------------------*/

  // 人物旋转
  function rotation(velocity) {
    const rotationAngle = Math.atan2(velocity.x, velocity.z); // 旋转角度
    const rotationEuler = euler().set(0, rotationAngle, 0); // 旋转欧拉角
    const rotationQuaternion = quat().setFromEuler(rotationEuler); // 旋转四元数
    const startQuaternion = quat().copy(playerRef.current.rotation()); // 当前旋转四元数

    startQuaternion.slerp(rotationQuaternion, 0.2);
    playerRef.current.setRotation(startQuaternion);
  }
  // 人物同步时击穿地面时重置y位置
  // function reset() {
  //   if (click) return;
  //   click = true;
  //   console.log("重置起始点：", start);
  //   const pos = playerRef.current.translation();
  //   if (pos.y < -5) {
  //     playerRef.current.setTranslation(start, true);
  //   }
  // }

  /*----------------------------模型渲染-------------------------------*/
  return (
    <group dispose={null}>
      <RigidBody
        mass={1}
        ref={playerRef}
        colliders={false}
        // type="dynamic"
        enabledRotations={[false, false, false]}
      >
        <primitive ref={ref} object={clone} position={[0, -1, 0]} />
        <CapsuleCollider args={[0.6, 0.3]} position={[0, -0.1, 0]} />
        <PositionalAudio
          ref={footsteps}
          url={audios.footsteps}
          distance={2}
          loop
          load
        />
      </RigidBody>
    </group>
  );
};
